package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
/**
 * 封装缓存工具类
 */
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);


    /**
     * 将传入电费任意对象序列化为JSON并存储和设置过期时间
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     */
    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,timeUnit);
    }

    /**
     * 将传入电费任意对象序列化为JSON并存储和设置逻辑过期时间
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     */
    public void setWithExpire(String key,Object value, Long time, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        redisData.setData(value);
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存穿透
     * @param id
     * @return
     */
    public <R,ID>R queryWithPassThrough
    (Class<R> type, String keyPrefix, ID id, Function<ID,R> dbFallback,Long time, TimeUnit timeUnit) {
        //1.根据id 在Redis中查询商铺缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }
        if(json != null){
            return null;
        }
        //3.未查到缓存，查询数据库.查询数据库的方式由调用者亲自编写
        R r = dbFallback.apply(id);
        //4.数据库无数据
        if(r == null){
            //向缓存中存入一个空值数据
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return  null;
        }
        //5.数据库有信息，将信息添加到缓存
        this.set(key,r,time,timeUnit);
        return r;
    }
    /**
     * 逻辑过期封装缓存击穿
     * @param id
     * @return
     */
    public <R,ID>R queryWithLogicalExpeire(ID id,String keyPrefix,Class<R> type,Function<ID,R> dbFallback,Long time, TimeUnit timeUnit) {
        //1.根据id 在Redis中查询商铺缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否命中缓存
        if (StrUtil.isBlank(json)){
            //3.未命中，返回空
            return null;
        }
        //4.命中缓存，需要吧JSON字符串反序列化为java对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r= JSONUtil.toBean(data,type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断缓存是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //5.1未过期，返回商户信息
            return r;
        }
        //5.2已过期，尝试获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.判断是否获取互斥锁
        if (isLock){
            //6.1成功获取，(二次检验逻辑时间是否过期)开启独立线程
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存=查询数据库+写入缓存
                    R r1 = dbFallback.apply(id);
                    this.set(key,r1,time,timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
        }
        //6.2未成功，返回过期商铺数据
        return r;
    }

    /**
     * 获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     * @param key
     */
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

}
